<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="120">
      <el-form-item label="作废原因">
        <el-input :maxlength="100" v-model="formData.invalidReason" placeholder="请输入作废原因" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as announceManage from '@/api/announceManage'
const emit = defineEmits(['success'])
const formRef = ref()
const { t } = useI18n()
const message = useMessage()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formData: Record<string, any> = ref({
  id: undefined,
  invalidReason: undefined
})

const open = async (id: number) => {
  resetFn()
  dialogVisible.value = true
  dialogTitle.value = '作废'
  formData.value.id = id
}

const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    formLoading.value = true
    await announceManage.invalid(formData.value)
    message.success(t('common.operateSuccess'))
    dialogVisible.value = false
    resetFn()
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetFn = () => {
  formData.value = {
    id: undefined,
    invalidReason: undefined
  }
  formRef.value?.resetFields()
}

defineExpose({ open })
</script>
